#include "Common.h"
#include "Window.h"
#include "DXUTgui.h"
#include "UIManager.h"

Window::WindowList Window::msWindowList;

static void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext)
{
	if (pUserContext == NULL)
		return;

	Window* window = static_cast<Window*>(pUserContext);
	window->FireEvent(nControlID, nEvent);
}

Window::Window()
	: mDialog(new CDXUTDialog())
{
	msWindowList.push_back(this);
}

Window::~Window()
{
	msWindowList.remove(this);

	for (ControlEvents::iterator it(mControlEvents.begin()), end(mControlEvents.end()); it != end; it++)
	{
		for (EventSlots::iterator slotIt(it->second.begin()), slotEnd(it->second.end()); slotIt != slotEnd; slotIt++)
			delete slotIt->second;
	}
	mControlEvents.clear();

	SAFE_DELETE(mDialog);
}

bool Window::Open()
{
	mDialog->Init(UIManager::Instance().getDialogResourceMgr());
	mDialog->SetCallback(OnGUIEvent, this);
	
    mDialog->SetFont( 1, L"Courier New", 16, FW_NORMAL );


	return OnOpen();
}

void Window::Destroy()
{
	OnDestory();

	UIManager::Instance().getDialogResourceMgr()->UnregisterDialog(mDialog);
	SAFE_DELETE(mDialog);
}

void Window::CloseAll()
{
	while (!msWindowList.empty())
		msWindowList.front()->Close();
}

bool Window::FireEvent(int id, UINT event, CDXUTControl* sender)
{
	ControlEvents::iterator it = mControlEvents.find(id);
	while (it != mControlEvents.end() && it->first == id)
	{
		EventSlots::iterator slotIt = it->second.find(event);
		while (slotIt != it->second.end() && slotIt->first == event)
		{
			if ((*slotIt->second)(sender))
				return true;
			slotIt++;
		}
		it++;
	}
	return false;
}
